package algorithm2_v3;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Task1 implements Callable<Object> {

	static Logger logger = LoggerFactory.getLogger(Task1.class);

	@Override
	public Object call() throws Exception {
		// logger.info("1. Ataza Martxan");
		// Thread.sleep(info.incarnation[0]+info.timeUnit[0]); //Delay hau
		// Iniciationen sartu da scheduler exekutatzerakoan
		
		ScheduledExecutorService executor = Executors
				.newSingleThreadScheduledExecutor();
		executor.scheduleAtFixedRate(new Runnable() {
			public void run() {
				Message message;
				try {
					if (SystemInfo.INSTANCE.leader.toString().equals(
							InetAddress.getLocalHost().getHostName())) {
						message = new Message("LEADER");
						message.sendMessages();
					} else if (SystemInfo.INSTANCE.leader.toString().equals("")) {
						message = new Message("ALIVE");
						message.sendMessages();
					}
				} catch (UnknownHostException e) {
					logger.info("ERROREA: Task1 mezua bidaltzean: -ari");
				}

			}
		}, 0, SystemInfo.INSTANCE.timeUnit[0], TimeUnit.MILLISECONDS);
		return null;
	}

}
